const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const { baseDataPath,pathType,status } = require('../src/config');
const { getData } = require('../src/fn');


/* GET data */
router.get('/', function(req, res, next) {
  let result = getData();
  // 判断result {} 是否有属性
  if(Object.keys(result).length > 0) {
    res.send(status({data:result}));
  }else{
    res.send(status({data:{},code:200,msg:'data目录为空'}));
  }
});


// UPDATE data 
router.post('/update', function(req, res, next) {
  // 获取文件名
  const {projectName,oldProjectName} = req.body;
  // 遍历data目录 忽略 .DS_Store
  const data = fs.readdirSync(baseDataPath).filter(item=>item != '.DS_Store');
  if(data.length > 0) {
    if(!data.includes(oldProjectName+'.json')) return res.send(status({code:400,msg:'项目不存在'}));
    const newFile = JSON.stringify({...req.body,build:{Android:false,Ios:false}});
    if(oldProjectName != projectName) {
      fs.renameSync(`${baseDataPath+pathType+oldProjectName}.json`, `${baseDataPath+pathType+projectName}.json`);
    }
    // 写入文件
    fs.writeFileSync(`${baseDataPath+pathType+projectName}.json`, newFile,'utf-8');
    res.send(status({code:200,msg:'修改成功'}));
  }else{
    res.send(status({code:400,msg:'data目录为空'}));
  }
});

// DELETE data
router.post('/delete', function(req, res, next) {
  // 获取文件名
  const {projectName} = req.body;
  // 遍历data目录
  const data = fs.readdirSync(baseDataPath).filter(item=>item != '.DS_Store');
  if(data.length > 0) {
    if(!data.includes(projectName+'.json')) return res.send(status({code:400,msg:'项目不存在'}));
    res.send(status({code:666,msg:'删除成功',data:projectName+'删除成功'}));
    fs.unlink(`${baseDataPath+pathType+projectName}.json`, (err) => {
      if (err) throw err;
      console.log('data数据已删除');
    });
    fs.rm(path.resolve(__dirname, '../src/project', projectName), { recursive: true, force: true }, (err) => {
      if (err) throw err;
      console.log('项目文件已删除');
    });
    fs.rm(path.resolve(__dirname, '../public/uploadfile', projectName), { recursive: true, force: true }, (err) => {
      if (err) throw err;
      console.log('上传目录已删除');
    });

  }else{
    res.send(status({code:400,msg:'data目录为空'}));
  }
});

// CREATE data
router.post('/create', function(req, res, next) {
  // 获取文件名
  const {projectName} = req.body;
  // 遍历data目录
  const data = fs.readdirSync(baseDataPath).filter(item=>item != '.DS_Store');
  if(data.length > 0) {
    if(data.includes(projectName+'.json')) return res.send(status({code:400,msg:'项目已存在'}));
    fs.writeFileSync(`${baseDataPath+pathType+projectName}.json`, JSON.stringify({...req.body,build:{Android:false,Ios:false}}),'utf-8');
    res.send(status({code:200,msg:'创建成功'}));
  }else{
    fs.writeFileSync(`${baseDataPath+pathType+projectName}.json`, JSON.stringify({...req.body,build:{Android:false,Ios:false}}),'utf-8');
    res.send(status({code:200,msg:'创建成功'}));

  }
});



module.exports = router;
